/*
 * @Author: szx
 * @Date: 2022-03-10 20:50:02
 * @LastEditTime: 2022-03-10 22:28:50
 * @Description:
 * @FilePath: \MDN_JS学习\测试\Promise限制并发.js
 */

// 并发数量计数
function get(i) {
    // console.log('In ', i);
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(i * 1000);
            console.log('Out', i, 'Out');
        }, i*500);
    });
}
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (let i = list.length - 1; i >= 0; i--) {
    get(list[i]);
}
function promiseConcurrencyLimit(limit, arr, fn) {
    function run(count) {
        if (count < arr.length) {
            fn(arr[count]).then(() => {
                run(count + limit);
            });
        }
    }
    for (let i = 0; i < limit; i++) run(i);
}

// promiseConcurrencyLimit(3, list, get);
// 执行顺序应该是
// 1 => 4 => 7 => 10
// 2 => 5 => 8
// 3 => 6 => 9
